import React, { useState, useMemo, useEffect, useCallback } from 'react'
import dayjs from 'dayjs'
import classNames from 'classnames'
import { observer, inject } from 'mobx-react'

import videoStore from '../../../store/video'
import recordTime from '../../../store/record-time'
import './time-area.scss'
import VideoPlayer from '../../common/video-player'
import useSubs from '../../../hooks/useSubs'
import common from '../../../store/common'

const RecordTime = () => {
  const { event$ } = common

  const [playProgress, setPlayProgress] = useState({ duration: 0, currentTime: 0 })
  const [isRecord, setIsRecord] = useState(true)

  const videoPlayerRef = useCallback((val) => {
    if (val) {
      //   console.log(val.playProgress)
    }
  })

  useEffect(() => {
    const time = recordTime.getTimeById(videoStore.curScreenId)
    if (time) {
      const { duration, currentTime } = time
      setPlayProgress({ duration, currentTime })
    }
  }, [recordTime.timeArray])

  // 聚焦分屏，获取分屏对应的时间信息
  useEffect(() => {
    getTimeInfo()
  }, [videoStore.curScreenId])

  useEffect(() => {
    const { currentTime, duration } = playProgress
    let pct = 0
    if (duration !== 0) {
      pct = (currentTime / duration).toFixed(2)
    }
    event$.emit({ action: 'setProgressLen', val: pct })
  }, [playProgress])

  useMemo(() => {
    videoStore.videoType === 'live' ? setIsRecord(false) : setIsRecord(true)
  }, [videoStore.videoType])

  useSubs(({ action, val }) => {
    if (action === 'resetTime') {
      setPlayProgress({ duration: 0, currentTime: 0 })
    }
    if (action === 'changeRecordTime') {
      const { duration } = playProgress
      const currentTime = duration * val.pct
      setPlayProgress({
        duration: playProgress.duration,
        currentTime,
      })
      const screen = videoStore.findScreenById(videoStore.curScreenId)
      if (screen) {
        const video = screen.player?.video
        if (video) {
          video.currentTime = currentTime
        }
      }
    }
  })

  function timeFormat() {
    const { currentTime, duration } = playProgress
    const cur = dayjs('2000-1-1').add(currentTime.toFixed(2), 's')
    const dua = dayjs('2000-1-1').add(duration.toFixed(2), 's')
    return `${cur.format('HH:mm:ss')} / ${dua.format('HH:mm:ss')}`
  }

  function getTimeInfo() {
    const time = recordTime.getTimeById(videoStore.curScreenId)
    if (time) {
      const { duration, currentTime } = time
      setPlayProgress({ duration, currentTime })
    } else {
      setPlayProgress({ duration: 0, currentTime: 0 })
    }
  }

  return (
    <>
      <VideoPlayer ref={videoPlayerRef} />
      <span className={classNames({ 'time-text': true, 'time-visible': isRecord, 'time-invisible': !isRecord })}>
        {timeFormat()}
      </span>
    </>
  )
}

export default inject('store')(observer(RecordTime))
